package electricity.service.impl;



import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import electricity.domain.DeviceInfo;
import electricity.domain.SysUser;
import electricity.dto.*;
import electricity.mapper.RoleMapper;
import electricity.mapper.SysUserMapper;
import electricity.mapper.UserRoleMapper;
import electricity.service.UserManageService;
import electricity.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserManageServiceImpl implements UserManageService{
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RoleMapper roleMapper;
//    @Autowired
//    private UserManageVO userManageVO;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 分页查询
     *
     * @param userManageQueryDto
     * @return
     */
    @Override
    public PageResult pageQuery(UserManageQueryDto userManageQueryDto) {
        int pageNum = userManageQueryDto.getPage() != null ? userManageQueryDto.getPage() : 1;
        int pageSize = userManageQueryDto.getPageSize() != null ? userManageQueryDto.getPageSize() : 10;

        PageHelper.startPage(pageNum,pageSize);
        Page<UserManageQueryVO> page = sysUserMapper.pageQuery(userManageQueryDto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public PageResult pageQuery(RoleQueryDto roleQueryDto) {
        int pageNum = roleQueryDto.getPage() != null ? roleQueryDto.getPage() : 1;
        int pageSize = roleQueryDto.getPageSize() != null ? roleQueryDto.getPageSize() : 10;

        PageHelper.startPage(pageNum,pageSize);
        Page<RoleManageVO> page = roleMapper.pageQuery(roleQueryDto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public UserManageVO update(UserUpdateDto userUpdateDto) {
        log.info("更新用户:{}", userUpdateDto);
        Integer userId = userUpdateDto.getId();
        // 1. 转换DTO为实体（不更新创建时间）
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userUpdateDto, sysUser);
//        // 密码加密（如果前端传递了新密码，则更新；否则不更新）
//        if (StringUtils.hasText(dto.getPassword())) {
//            sysUser.setPassword(bcryptPasswordEncoder.encode(dto.getPassword()));
//        }

        // 2. 更新用户表基本信息
        sysUserMapper.updateByPrimaryKey(sysUser);

        // 3. 先删除旧角色关联，再插入新关联
        userRoleMapper.deleteByUserId(userId);
        if (userUpdateDto.getRoleIds() != null && !userUpdateDto.getRoleIds().isEmpty()) {
            userRoleMapper.batchInsert(userId, userUpdateDto.getRoleIds());
        }

        // 4. 转换为VO返回
        UserManageVO vo = new UserManageVO();
        SysUser updatedUser = sysUserMapper.selectByPrimaryKey(userId);
        BeanUtils.copyProperties(updatedUser, vo);
        vo.setRoleIds(userUpdateDto.getRoleIds());  // 回显新角色ID列表
        return vo;
    }

    @Override
    public UserManageVO insert(UserUpdateDto userUpdateDto) {
        log.info("新增用户：{}", userUpdateDto);

        // 1. 转换DTO为实体，设置创建时间
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userUpdateDto, sysUser);
        sysUser.setId(null); // 显式设置为 null，确保不传递 id
        sysUser.setCreateTime(new Date());  // 后端生成创建时间
//        // 密码加密（建议添加，如BCrypt加密）
//        sysUser.setPassword(bcryptPasswordEncoder.encode(dto.getPassword()));

        // 2. 插入用户表，获取自增ID
        sysUserMapper.insert(sysUser);
        Integer userId = sysUser.getId();  // 插入后自动回填ID

        // 3. 关联角色（如果有角色）
        if (userUpdateDto.getRoleIds() != null && !userUpdateDto.getRoleIds().isEmpty()) {
            userRoleMapper.batchInsert(userId, userUpdateDto.getRoleIds());
        }

        // 4. 转换为VO返回
        UserManageVO vo = new UserManageVO();
        BeanUtils.copyProperties(sysUser, vo);
        vo.setRoleIds(userUpdateDto.getRoleIds());  // 回显角色ID列表
        return vo;
    }

    @Override
    public List<RoleVO> getRole() {
        return roleMapper.selectAllRoles();
    }

    @Override
    public void batchDelete(List<Integer> ids) {
        // 1. 批量删除中间表关联
        ids.forEach(userId -> userRoleMapper.deleteByUserId(userId));
        // 2. 批量删除用户表记录
        int deleteCount = sysUserMapper.deleteBatchIds(ids);
        if (deleteCount != ids.size()) {
            throw new RuntimeException("部分用户不存在或已被删除，删除失败");
        }
    }


    @Override
    public String userSearch(SysUser sysUser) {
        return "";
    }



    @Override
    public void userDelete(Integer userId) {

        // 1. 先删除中间表关联记录（避免外键约束报错）
        userRoleMapper.deleteByUserId(userId);

        // 2. 再删除用户表记录
        int deleteCount = sysUserMapper.deleteById(userId);

        // 3. 校验是否删除成功
        if (deleteCount == 0) {
            throw new RuntimeException("删除失败，用户不存在或已被删除");
        }
    }
}
